package com.hnu.store.utils;

import com.hnu.store.entity.Trade;
import com.hnu.store.entity.User;
import com.hnu.store.entity.Work;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;


public class PdfUtils {

  //  使用权证书生成
  public String useRightCertificatePdfOut(Work work, Trade trade, User user) {
    Map<String, String> map = new HashMap<>();

    map.put("realName", user.getRealName());
    map.put("NftName", work.getWorkName());
    map.put("fileHash", work.getFileHash());
    map.put("pocketAddress", user.getPocket());
    map.put("txHash", trade.getTxHash());
    map.put("time", LocalDate.now().toString());
    // 模板路径
    String templatePath = System.getProperty("user.dir") + File.separator + "UseRightTemplate.pdf";
    String fontPath = System.getProperty("user.dir") + File.separator + "msyh.ttc,1";
    String outputPath =
        System.getProperty("user.dir") + File.separator + "nftTradeCertificate" + File.separator
            + trade.getTxHash();
    File fileDir = new File(outputPath);
    if (!fileDir.exists() && !fileDir.isDirectory()) {
      fileDir.mkdirs();
    }

    // 生成的新文件路径
    String newPDFPath = outputPath + File.separator + "UseRightCertificate.pdf";
    //  生成pdf的工具与流对象
    PdfReader reader;
    FileOutputStream out;
    ByteArrayOutputStream bos;
    PdfStamper stamper;

    try {
      BaseFont bf = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
      //  输出流
      out = new FileOutputStream(newPDFPath);
      //  读取pdf模板
      reader = new PdfReader(templatePath);
      bos = new ByteArrayOutputStream();
      stamper = new PdfStamper(reader, bos);
      AcroFields form = stamper.getAcroFields();
      //  文字内容处理
      form.addSubstitutionFont(bf);
      for (String key : map.keySet()) {
        String value = map.get(key);
        form.setField(key, value);
      }
      //  如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
      stamper.setFormFlattening(true);
      stamper.close();
      Document doc = new Document();
      PdfCopy copy = new PdfCopy(doc, out);
      doc.open();
      PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
      copy.addPage(importPage);
      doc.close();
      return outputPath;
    } catch (IOException | DocumentException e) {
      System.out.println("生成使用权证书失败,可能出现io错误");
      throw new RuntimeException();
    }
  }

  //  所有权证书生成
  public String ownerShipCertificatePdfOut(Work work, Trade trade, User user, String chainTime,
      String blockHeight) {
    Map<String, String> map = new HashMap<>();

    map.put("NftName", work.getWorkName());
    map.put("fileHash", work.getFileHash());
    map.put("txHash", trade.getTxHash());
    map.put("chainName", "CONFLUX");
    map.put("blockHeight", blockHeight);
    map.put("chainTime", chainTime);
    map.put("realName", user.getRealName());
    map.put("citizenId", user.getCitizenId());
    map.put("time", LocalDate.now().toString());
    // 模板路径
    String templatePath = System.getProperty("user.dir") + File.separator + "OwnershipTemplate.pdf";
    String fontPath = System.getProperty("user.dir") + File.separator + "msyh.ttc,1";
    String outputPath =
        System.getProperty("user.dir") + File.separator + "nftTradeCertificate" + File.separator
            + trade.getTxHash();
    File fileDir = new File(outputPath);
    if (!fileDir.exists() && !fileDir.isDirectory()) {
      fileDir.mkdirs();
    }

    // 生成的新文件路径
    String newPDFPath = outputPath + File.separator + "OwnershipCertificate.pdf";
    //  生成pdf的工具与流对象
    PdfReader reader;
    FileOutputStream out;
    ByteArrayOutputStream bos;
    PdfStamper stamper;

    try {
      BaseFont bf = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
      //  输出流
      out = new FileOutputStream(newPDFPath);
      //  读取pdf模板
      reader = new PdfReader(templatePath);
      bos = new ByteArrayOutputStream();
      stamper = new PdfStamper(reader, bos);
      AcroFields form = stamper.getAcroFields();
      //  文字内容处理
      form.addSubstitutionFont(bf);
      for (String key : map.keySet()) {
        String value = map.get(key);
        form.setField(key, value);
      }
      //  如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
      stamper.setFormFlattening(true);
      stamper.close();
      Document doc = new Document();
      PdfCopy copy = new PdfCopy(doc, out);
      doc.open();
      PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
      copy.addPage(importPage);
      doc.close();
      return outputPath;
    } catch (IOException | DocumentException e) {
      System.out.println("生成使用权证书失败,可能出现io错误");
      throw new RuntimeException();
    }
  }

  //  链上存证证明生成
  public String depositCertificatePdfOut(Work work, User user, String chainTime,
      String blockHeight) {
    Map<String, String> map = new HashMap<>();

    map.put("type", work.getCopyrightOwnerType() == 1 ? "自然人"
        : work.getCopyrightOwnerType() == 2 ? "企业法人" : work.getCopyrightOwnerType() == 3 ? "机关法人"
            : work.getCopyrightOwnerType() == 4 ? "事业单位法人"
                : work.getCopyrightOwnerType() == 5 ? "社会团体法人" : "其他");
    map.put("realName", user.getRealName());
    map.put("citizenId", user.getCitizenId());
    map.put("NftName", work.getWorkName());
    map.put("fileHash", work.getFileHash());
    map.put("txHash", work.getChainHash());
    map.put("chainName", "CONFLUX");
    map.put("blockHeight", blockHeight);
    map.put("chainTime", chainTime);
    map.put("time", LocalDate.now().toString());

    // 模板路径
    String templatePath = System.getProperty("user.dir") + File.separator + "NFTTemplate.pdf";
    String fontPath = System.getProperty("user.dir") + File.separator + "msyh.ttc,1";
    String outputPath =
        System.getProperty("user.dir") + File.separator + "nftFile" + File.separator
            + work.getId();

    File fileDir = new File(outputPath);
    if (!fileDir.exists() && !fileDir.isDirectory()) {
      fileDir.mkdirs();
    }

    // 生成的新文件路径
    String newPDFPath = outputPath + File.separator + "NFTCertificate.pdf";
    //  生成pdf的工具与流对象
    PdfReader reader;
    FileOutputStream out;
    ByteArrayOutputStream bos;
    PdfStamper stamper;

    try {
      BaseFont bf = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
      //  输出流
      out = new FileOutputStream(newPDFPath);
      //  读取pdf模板
      reader = new PdfReader(templatePath);
      bos = new ByteArrayOutputStream();
      stamper = new PdfStamper(reader, bos);
      AcroFields form = stamper.getAcroFields();
      //  文字内容处理
      form.addSubstitutionFont(bf);
      for (String key : map.keySet()) {
        String value = map.get(key);
        form.setField(key, value);
      }
      //  如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
      stamper.setFormFlattening(true);
      stamper.close();
      Document doc = new Document();
      PdfCopy copy = new PdfCopy(doc, out);
      doc.open();
      PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
      copy.addPage(importPage);
      doc.close();
      return outputPath;
    } catch (IOException | DocumentException e) {
      System.out.println("生成使用权证书失败,可能出现io错误");
      throw new RuntimeException();
    }
  }
}
